package com.qf.smsplatform.strategy.executor;

import com.qf.smsplatform.common.constants.CacheConstants;
import com.qf.smsplatform.common.enums.SmsEnum;
import com.qf.smsplatform.common.exception.SmsException;
import com.qf.smsplatform.common.model.StandardSubmit;
import com.qf.smsplatform.strategy.client.CacheClient;
import com.qf.smsplatform.strategy.strategy.Strategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;
/**
 * projectName: smsplatform
 *
 * @author: MaTianWei
 * time: 2021/8/12 19:49
 * description:策略链执行者,指定策略链的执行顺序
 */
@Component
@Slf4j
public class StrategyExecutor {
    //需要拿到所有的策略对象
    @Autowired
    private Map<String, Strategy> strategyMap;
    //调用缓存模块的fegin接口
    @Autowired
    private CacheClient cacheClient;

    public void execute(StandardSubmit submit){
        //1从其他位置获取到策略对象的执行顺序
        String filters = cacheClient.hget(CacheConstants.CACHE_PREFIX_CLIENT + submit.getClientID(),"filters");
        //2根据执行顺序依次执行每一个策略的execute方is并根据结果返回结果,判断是否需要执行下一个
        if(StringUtils.isEmpty(filters)){
            log.info("[策略模块-执行策略] 无法查询到当前客户的执行策略链的执行顺序! filters = {}",filters);
            throw new SmsException(SmsEnum.ERROR);
        }
        String[] filterArray = filters.split(",");
        for (String filter : filterArray){
            Strategy strategy = strategyMap.get(filter);
            if (strategy != null){
                boolean flag = strategy.execute(submit);
                if(!flag){
                    return;
                }
            }
        }
    }
}